// API服务封装
import { config } from '@/config/api.js'

const BASE_URL = config.BASE_URL

// 自动登录函数
const handleTokenExpired = () => {
  return new Promise((resolve, reject) => {
    // 使用固定账号自动登录
    uni.request({
      url: BASE_URL + '/api/auth/miniapp/login',
      method: 'POST',
      data: {
        username: 'admin',
        password: 'admin123'
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 保存新的token
          uni.setStorageSync('token', res.data.data.token)
          uni.setStorageSync('userInfo', res.data.data.userInfo)
          resolve()
        } else {
          reject(res.data)
        }
      },
      fail: reject
    })
  })
}

// 重试请求函数
const retryRequest = (options) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    const url = options.url.startsWith('http') ? options.url : BASE_URL + options.url
    
    const requestOptions = {
      url: url,
      method: options.method || 'GET',
      header: {
        'Content-Type': 'application/json',
        ...(token ? { 'Authorization': 'Bearer ' + token } : {}),
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: reject
    }

    // 添加请求体
    if (options.data) {
      if (options.method === 'GET') {
        const params = buildQueryString(options.data)
        requestOptions.url += (requestOptions.url.includes('?') ? '&' : '?') + params
      } else {
        requestOptions.data = options.data
      }
    }

    uni.request(requestOptions)
  })
}

// 构建查询字符串（替代URLSearchParams）
const buildQueryString = (params) => {
  if (!params || typeof params !== 'object') return ''
  
  const queryParts = []
  for (const key in params) {
    if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== undefined) {
      queryParts.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
    }
  }
  return queryParts.join('&')
}

// 请求拦截器
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 显示加载提示
    if (options.loading !== false) {
      uni.showLoading({
        title: options.loadingText || '加载中...',
        mask: true
      })
    }

    // 构建完整URL
    const url = options.url.startsWith('http') ? options.url : BASE_URL + options.url
    
    // 获取认证Token
    const token = uni.getStorageSync('token')
    
    // 构建请求参数
    const requestOptions = {
      url: url,
      method: options.method || 'GET',
      header: {
        'Content-Type': 'application/json',
        // 添加认证头
        ...(token ? { 'Authorization': 'Bearer ' + token } : {}),
        ...options.header
      },
      success: (res) => {
        uni.hideLoading()
        
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data)
          } else if (res.data.code === 401) {
            // Token过期，尝试自动登录
            handleTokenExpired().then(() => {
              // 重新发起请求
              retryRequest(options).then(resolve).catch(reject)
            }).catch(() => {
              uni.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none'
              })
              reject(res.data)
            })
          } else {
            uni.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.hideLoading()
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(err)
      }
    }

    // 添加请求体
    if (options.data) {
      if (options.method === 'GET') {
        // GET请求将参数拼接到URL
        const params = buildQueryString(options.data)
        requestOptions.url += (requestOptions.url.includes('?') ? '&' : '?') + params
      } else {
        requestOptions.data = options.data
      }
    }

    uni.request(requestOptions)
  })
}

// 重点工作相关API
export const workApi = {
  // 获取重点工作列表
  getWorkList(params = {}) {
    return request({
      url: '/api/work/list',
      method: 'GET',
      data: {
        pageNum: params.pageNum || 1,
        pageSize: params.pageSize || 10,
        status: params.status || 'all',
        title: params.title || '',
        department: params.department || ''
      }
    })
  },

  // 获取重点工作详情
  getWorkDetail(id) {
    return request({
      url: `/api/work/detail/${id}`,
      method: 'GET'
    })
  },

  // 更新工作进度
  updateWorkProgress(id, data) {
    return request({
      url: `/api/work/progress/${id}`,
      method: 'PUT',
      data: data
    })
  }
}

// 反馈相关API
export const feedbackApi = {
  // 获取反馈列表
  getFeedbackList(params = {}) {
    return request({
      url: '/api/feedback/list',
      method: 'GET',
      data: {
        pageNum: params.pageNum || 1,
        pageSize: params.pageSize || 10,
        status: params.status || 'all',
        phone: params.phone || '',
        name: params.name || '',
        type: params.type || ''
      }
    })
  },

  // 提交问题反馈
  submitFeedback(data) {
    return request({
      url: '/api/feedback/submit',
      method: 'POST',
      data: data,
      loadingText: '提交中...'
    })
  },

  // 获取反馈详情
  getFeedbackDetail(id) {
    return request({
      url: `/api/feedback/detail/${id}`,
      method: 'GET'
    })
  },

  // 处理反馈问题
  handleFeedback(id, data) {
    return request({
      url: `/api/feedback/handle/${id}`,
      method: 'PUT',
      data: data
    })
  }
}

// 文件上传相关API
export const uploadApi = {
  // 单张图片上传
  uploadImage(filePath) {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: BASE_URL + '/common/upload',
        filePath: filePath,
        name: 'file',
        header: {
          // 这里需要添加认证头，如果有的话
          // 'Authorization': 'Bearer ' + token
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              resolve(data)
            } else {
              uni.showToast({
                title: data.msg || '上传失败',
                icon: 'none'
              })
              reject(data)
            }
          } catch (e) {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            })
            reject(e)
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(err)
        }
      })
    })
  },

  // 批量图片上传
  uploadImages(filePaths) {
    return new Promise((resolve, reject) => {
      const uploadPromises = filePaths.map(filePath => uploadApi.uploadImage(filePath))
      
      Promise.all(uploadPromises)
        .then(results => {
          resolve({
            code: 200,
            msg: '批量上传成功',
            data: results.map(result => result.data)
          })
        })
        .catch(err => {
          reject(err)
        })
    })
  },

  // 删除图片
  deleteImage(fileName) {
    return request({
      url: '/common/upload/delete',
      method: 'DELETE',
      data: { fileName }
    })
  }
}

// 通用API
export const commonApi = {
  // 获取问题类型列表
  getProblemTypes() {
    return request({
      url: '/api/common/problem-types',
      method: 'GET'
    })
  },

  // 获取状态枚举
  getStatusEnums() {
    return request({
      url: '/api/common/status-enums',
      method: 'GET'
    })
  }
}

// 无token请求方法（用于公开接口）
const requestWithoutToken = (options) => {
  return new Promise((resolve, reject) => {
    // 显示加载提示
    if (options.loading !== false) {
      uni.showLoading({
        title: options.loadingText || '加载中...',
        mask: true
      })
    }

    // 构建完整URL
    const url = options.url.startsWith('http') ? options.url : BASE_URL + options.url
    
    // 构建请求参数（不添加token）
    const requestOptions = {
      url: url,
      method: options.method || 'GET',
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        uni.hideLoading()
        
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data)
          } else {
            uni.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.hideLoading()
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(err)
      }
    }

    // 添加请求体
    if (options.data) {
      if (options.method === 'GET') {
        const params = buildQueryString(options.data)
        requestOptions.url += (requestOptions.url.includes('?') ? '&' : '?') + params
      } else {
        requestOptions.data = options.data
      }
    }

    uni.request(requestOptions)
  })
}

// 乡村介绍相关API
export const villageApi = {
  // 获取乡村介绍信息（无需token）
  getVillageIntro() {
    return requestWithoutToken({
      url: '/api/village/intro',
      method: 'GET',
      loading: false // 乡村介绍页面不需要显示loading
    })
  },
  
  // 自动登录
  autoLogin() {
    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + '/api/auth/miniapp/login',
        method: 'POST',
        data: {
          username: 'admin',
          password: 'admin123'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: reject
      })
    })
  }
}

// 工具函数
export const utils = {
  // 处理图片URL，添加完整路径
  getImageUrl(url) {
    if (!url) return ''
    if (url.startsWith('http')) return url
    return BASE_URL + url
  },

  // 处理图片URLs字符串，转换为数组
  parseImageUrls(urls) {
    if (!urls) return []
    if (Array.isArray(urls)) return urls
    return urls.split(',').filter(url => url.trim())
  },

  // 将图片数组转换为URLs字符串
  stringifyImageUrls(images) {
    if (!images || !Array.isArray(images)) return ''
    return images.filter(url => url.trim()).join(',')
  },

  // 手机号脱敏
  maskPhone(phone) {
    if (!phone) return ''
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
}
